/*
 * Copyright (c)  2018, Marmot
 * All rights reserved. 
 *
 * Id:RedisService.java   2018-06-11 17:22 wanglijun
 */
package io.marmot.core;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: Copyright (c) 2018
 * </p>
 * <p>
 * Company: Marmot
 * </p>
 *
 * @author: wanglijun
 * @create: 2018-06-11 17:22
 * @version：1.0
 */
public  abstract  class AbstractRedisService<T>{

    @Autowired
    protected RedisTemplate<String,Object> redisTemplate;

    @Resource
    private HashOperations<String, String, T> hashOperations;


    protected abstract  String getRedisKey();


    public void put(String key,T doamin,Long expire) {
        hashOperations.put(this.getRedisKey (),key,doamin);
        if(expire!=-1){
            redisTemplate.expire (getRedisKey (),expire, TimeUnit.SECONDS);
        }
    }


    public void remove(String key){
        hashOperations.delete (getRedisKey (),key);
    }

    public T get(String key){
        return hashOperations.get (getRedisKey (),key);
    }

    public List<T> getAll(){
        return hashOperations.values (getRedisKey ());
    }

    public Boolean isKeyExists(String key){
        return hashOperations.hasKey (getRedisKey (),key);
    }


    public void clear() {
        Set<String> keys = hashOperations.keys (this.getRedisKey ());
        keys.stream ().forEach (key -> hashOperations.delete (getRedisKey (), key));
    }


    public Set<String> keys(){
            return  hashOperations.keys (this.getRedisKey ());
    }
}
